/**
 * 
 */
package com.jiang.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * @author Administrator
 * @Cookie 操作工具类
 */
public class CookieUtils {

	// 不能new, 这个是工具类
	private CookieUtils() {

	}

	/**
	 * @设置Cookie的方法
	 * @param request
	 * @param response
	 * @param key
	 * @param value
	 * @param maxAge
	 */
	public static boolean setCookie(HttpServletRequest request, HttpServletResponse response, String key, String value,
			int maxAge) {

		boolean flag = false;
		if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
			Cookie cookie = new Cookie(key, value);
			cookie.setPath(request.getContextPath());
			cookie.setMaxAge(maxAge);
			response.addCookie(cookie);
			flag = true;
		}
		return flag;
	}

	/**
	 * @清除所有Cookie的操作
	 * @param request
	 * @param response
	 * @param key
	 * @return
	 */
	public static boolean clearCookie(HttpServletRequest request, HttpServletResponse response) {

		boolean flag = false;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				// 别删除了Session了
				if (!cookie.getName().equals("JSESSIONID")) {
					cookie.setPath(request.getContextPath());
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
			flag = true;
		}
		return flag;
	}

}
